<template>
  <view class="file">
    <view class="list" :class="[getClass]">
      <view class="listItem" v-for="(item, index) of fileList" :key="index">
        <view class="listBox">
          <view class="box">
            <i
              v-if="!disabled"
              class="iconfont icon-reeor"
              @click="$emit('remove', index)"
            ></i>

            <image
              v-if="fileMediatype === 'image'"
              class="img"
              @click="see(index)"
              :src="item.url"
              mode="aspectFill"
            ></image>
            <video
              v-else
              :custom-cache="false"
              class="video"
              id="video"
              ref="video"
              controls
              :src="item.url"
            ></video>
          </view>
        </view>
      </view>

      <view
        class="listItem"
        v-show="!disabled && fileList.length < max"
        @click="file"
      >
        <view class="listBox">
          <view class="box">
            <i class="iconfont icon-add-select"></i>
            <view class="fileText">{{ getFileText }}</view>
          </view>
        </view>
      </view>
    </view>

    <toolsPreviewImage
      ref="toolsPreviewImage"
      :list="fileList"
      :current="current"
    ></toolsPreviewImage>
  </view>
</template>

<script>
import toolsPreviewImage from "@/components/tools/tools-previewImage";
import videoClassify from "@/api/videoClassify";

export default {
  components: {
    toolsPreviewImage
  },

  props: {
    fileList: {
      type: Array,
      default() {
        return [];
      }
    },

    fileMediatype: {
      type: String,
      default: "image"
    },

    disabled: {
      type: Boolean,
      default: false
    },

    max: {
      type: Number,
      default: 9
    },

    fileText: {
      type: String,
      default: ""
    },

    sourceType: {
      type: Array,
      default() {
        return ["album", "camera"];
      }
    },

    sizeType: {
      type: Array,
      default() {
        return ["original", "compressed"];
      }
    }
  },

  computed: {
    getClass() {
      return this.fileMediatype !== "image" ? "videoStyle" : "";
    },

    getFileText() {
      if (this.fileText) {
        return this.fileText;
      }

      let title;

      switch (this.fileMediatype) {
        case "image":
          title = this.$t("file.images");
          break;

        case "video":
          title = this.$t("file.video");
          break;
      }

      return title;
    }
  },

  data() {
    return {
      current: 0
    };
  },

  methods: {
    getVideoPoster(url) {
      let video = document.createElement("video");
      video.setAttribute("crossOrigin", "Anonymous"); // 处理跨域，H5需后台支持，请求的视频资源响应投标需有Access-Control-Allow-Origin
      video.setAttribute("src", url);
      video.setAttribute("width", 400);
      video.setAttribute("height", 500);
      video.setAttribute("preload", "auto");
      // uni.chooseVideo选择视频，当选用手机拍摄的视频时，地址是相对地址，如 _doc/uniapp_temp_1650594368317/camera/1650594390147.mp4
      // 可播放，但是loadeddata一直不执行，会触发error事件，视频加载失败
      // 应先转换成本地地址
      video.addEventListener("loadeddata", () => {
        let canvas = document.createElement("canvas");
        let width = video.width; // canvas的尺寸和图片一样
        let height = video.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(video, 0, 0, width, height); // 绘制canvas
        const dataURL = canvas.toDataURL("image/jpeg"); // 转换为base64

        videoClassify
          .uploadBase64({
            base64img: dataURL
          })
          .then((res) => {
            if (res.code == 0) {
              this.$emit("successCover", res.url);
            }
          })
          .catch(() => {});
      });

      video.addEventListener("error", (err) => {
      });
    },

    see(index) {
      this.current = index;
      uni.previewImage({
        current: index,
        urls: this.fileList.map((el) => el.url)
      });
      // setTimeout(() => {
      //   this.$refs.toolsPreviewImage.showPopup = true;
      // }, 300);
    },

    file() {
      let { fileMediatype, max, sourceType, fileList, sizeType } = this;
      switch (fileMediatype) {
        case "image":
          this.$utils.uploadImage(
            max - fileList.length,
            (res) => {
              this.$emit("success", res);
            },
            () => {},
            sizeType,
            sourceType
          );
          break;

        case "video":
          // #ifdef MP-WEIXIN
          uni.chooseMedia({
            count: max - fileList.length,
            sourceType,
            sizeType,
            mediaType: ["video"],
            success: (res) => {
              if (res.errMsg == "chooseMedia:ok") {
                var { tempFilePath, thumbTempFilePath } = res.tempFiles[0];
                this.$http.UPLOAD_VIDEO(tempFilePath, (res) => {
                  if (res.code == 0) {
                    this.$emit("success", res.url);
                  } else {
                    uni.showToast({
                      title: res.msg,
                      icon: "none",
                      duration: 2000
                    });
                  }
                });

                this.$http.UPLOAD_IMAGE(thumbTempFilePath, (res) => {
                  if (res.code == 0) {
                    this.$emit("successCover", res.url);
                  } else {
                    uni.showToast({
                      title: res.msg,
                      icon: "none",
                      duration: 2000
                    });
                  }
                });
              }
            },
            file: (res) => {}
          });
          // #endif
          // #ifndef MP-WEIXIN
          uni.chooseVideo({
            count: max - fileList.length,
            sourceType,
            sizeType,
            success: (res) => {
              if (res.errMsg == "chooseVideo:ok") {
                var tempFilePaths = res.tempFilePath;

                this.$http.UPLOAD_VIDEO(tempFilePaths, (res) => {
                  if (res.code == 0) {
                    this.$emit("success", res.url);

                    // #ifdef H5
                    this.getVideoPoster(res.url);
                    // #endif
                  } else {
                    uni.showToast({
                      title: res.msg,
                      icon: "none",
                      duration: 2000
                    });
                  }
                });
              }
            },
            file: (res) => {}
          });
          // #endif
          break;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.list {
  display: flex;
  flex-wrap: wrap;
  margin: -5rpx;

  .listItem {
    padding: 5rpx;
    width: 33.33%;
  }

  .listBox {
    position: relative;
    padding-top: 96%;
    background: #f2f2f2;
    border-radius: 10rpx;
    overflow: hidden;
  }

  .box {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }

  .img {
    width: 100%;
    height: 100%;
  }
}

.icon-add-select {
  font-size: 80rpx;
  color: #8c8c8c;
}

.fileText {
  padding-top: 5rpx;
  font-size: 24rpx;
  color: #8c8c8c;
}

.videoStyle {
  .listItem {
    width: 100%;
  }

  .listBox {
    padding-top: 50%;
  }
}

video {
  width: 100%;
  height: 100%;
  background: #000;
}

.icon-reeor {
  position: absolute;
  right: 5rpx;
  top: 5rpx;
  z-index: 9;
  font-size: 50rpx;
  color: #fff;
}
</style>
